<template>
  <div class="student-list-container">
    <el-card class="filter-container">
      <el-form :inline="true" :model="queryParams" class="filter-form">
        <el-form-item label="学号">
          <el-input v-model="queryParams.studentNo" placeholder="请输入学号" clearable />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="queryParams.name" placeholder="请输入姓名" clearable />
        </el-form-item>
        <el-form-item label="班级">
          <el-select v-model="queryParams.classId" placeholder="请选择班级" clearable>
            <el-option v-for="item in classList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-container">
      <template #header>
        <div class="table-header">
          <div class="title">学生列表</div>
          <div class="operations">
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>
              添加学生
            </el-button>
            <el-button type="success" @click="handleExport">
              <el-icon><Download /></el-icon>
              导出Excel
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="studentList"
        stripe
        border
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column type="index" width="50" label="序号" />
        <el-table-column prop="studentNo" label="学号" width="120" show-overflow-tooltip />
        <el-table-column prop="name" label="姓名" width="100" show-overflow-tooltip />
        <el-table-column prop="gender" label="性别" width="60">
          <template #default="scope">
            {{ scope.row.gender === 1 ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column prop="age" label="年龄" width="60" />
        <el-table-column prop="className" label="班级" width="120" show-overflow-tooltip />
        <el-table-column prop="phone" label="联系电话" width="120" show-overflow-tooltip />
        <el-table-column prop="email" label="电子邮箱" min-width="150" show-overflow-tooltip />
        <el-table-column prop="address" label="家庭住址" min-width="200" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" width="180" show-overflow-tooltip />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button 
              type="primary" 
              link 
              size="small" 
              @click="handleEdit(scope.row)"
            >
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button 
              type="primary" 
              link 
              size="small" 
              @click="handleView(scope.row)"
            >
              <el-icon><View /></el-icon>
              查看
            </el-button>
            <el-button 
              type="danger" 
              link 
              size="small" 
              @click="handleDelete(scope.row)"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 查看学生详情对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="学生详情"
      width="600px"
      destroy-on-close
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="学号">{{ currentStudent.studentNo }}</el-descriptions-item>
        <el-descriptions-item label="姓名">{{ currentStudent.name }}</el-descriptions-item>
        <el-descriptions-item label="性别">{{ currentStudent.gender === 1 ? '男' : '女' }}</el-descriptions-item>
        <el-descriptions-item label="年龄">{{ currentStudent.age }}</el-descriptions-item>
        <el-descriptions-item label="班级">{{ currentStudent.className }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ currentStudent.phone }}</el-descriptions-item>
        <el-descriptions-item label="电子邮箱" :span="2">{{ currentStudent.email }}</el-descriptions-item>
        <el-descriptions-item label="家庭住址" :span="2">{{ currentStudent.address }}</el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">{{ currentStudent.createTime }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
/**
 * 学生列表页面
 * 展示学生信息列表，支持查询、新增、编辑、删除等操作
 */
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getStudentList, deleteStudent } from '@/api/student'

export default {
  name: 'StudentList',
  setup() {
    const router = useRouter()
    
    // 加载状态
    const loading = ref(false)
    // 学生列表数据
    const studentList = ref([])
    // 班级列表
    const classList = ref([
      { id: 1, name: '计算机科学1班' },
      { id: 2, name: '计算机科学2班' },
      { id: 3, name: '软件工程1班' },
      { id: 4, name: '软件工程2班' }
    ])
    // 总数
    const total = ref(0)
    
    // 查询参数
    const queryParams = reactive({
      pageNum: 1,
      pageSize: 10,
      studentNo: '',
      name: '',
      classId: undefined
    })
    
    // 当前选中的学生
    const currentStudent = ref({})
    // 查看对话框可见性
    const viewDialogVisible = ref(false)
    
    // 初始化
    onMounted(() => {
      fetchStudentList()
    })
    
    // 获取学生列表
    const fetchStudentList = () => {
      loading.value = true
      
      // 调用后端API
      getStudentList(queryParams).then(res => {
        // 处理响应数据
        studentList.value = res.records || []
        total.value = res.total || 0
        
        // 格式化性别显示，后端返回的是字符串，前端需要转为数字以适配现有代码
        studentList.value.forEach(item => {
          if (item.gender === "男") {
            item.gender = 1
          } else if (item.gender === "女") {
            item.gender = 2
          }
          
          // 确保有班级ID用于筛选
          if (!item.classId && item.className) {
            // 根据班级名称找对应ID
            const classItem = classList.value.find(c => c.name === item.className)
            if (classItem) {
              item.classId = classItem.id
            }
          }
        })
      }).catch(err => {
        console.error('获取学生列表失败', err)
        ElMessage.error('获取学生列表失败')
      }).finally(() => {
        loading.value = false
      })
    }
    
    // 处理查询
    const handleQuery = () => {
      queryParams.pageNum = 1
      fetchStudentList()
    }
    
    // 重置查询条件
    const resetQuery = () => {
      queryParams.studentNo = ''
      queryParams.name = ''
      queryParams.classId = undefined
      handleQuery()
    }
    
    // 处理每页数量变化
    const handleSizeChange = (val) => {
      queryParams.pageSize = val
      fetchStudentList()
    }
    
    // 处理页码变化
    const handleCurrentChange = (val) => {
      queryParams.pageNum = val
      fetchStudentList()
    }
    
    // 添加学生
    const handleAdd = () => {
      router.push('/student/add')
    }
    
    // 编辑学生
    const handleEdit = (row) => {
      router.push(`/student/edit/${row.id}`)
    }
    
    // 查看学生详情
    const handleView = (row) => {
      currentStudent.value = row
      viewDialogVisible.value = true
    }
    
    // 删除学生
    const handleDelete = (row) => {
      ElMessageBox.confirm(`确定要删除学生"${row.name}"吗？`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteStudent(row.id).then(() => {
          ElMessage.success('删除成功')
          fetchStudentList()
        }).catch(err => {
          console.error('删除学生失败', err)
          ElMessage.error('删除学生失败')
        })
      }).catch(() => {})
    }
    
    // 导出Excel
    const handleExport = () => {
      ElMessage.success('导出成功')
    }
    
    return {
      loading,
      studentList,
      classList,
      total,
      queryParams,
      currentStudent,
      viewDialogVisible,
      handleQuery,
      resetQuery,
      handleSizeChange,
      handleCurrentChange,
      handleAdd,
      handleEdit,
      handleView,
      handleDelete,
      handleExport
    }
  }
}
</script>

<style scoped>
.student-list-container {
  min-height: 100%;
}

.filter-container {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.operations {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 